package com.hanliy.storage;

import com.hanliy.entity.PicStorageEntity;
import com.hanliy.service.StorageService;
import com.hanliy.util.CharUtil;
import lombok.Data;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * @author hanyulin
 * @apiNote 基本的图片存储服务类,负责对图片存储以及图片信息存储的转发
 * @date 2021/12/3 16:27
 */
@Data
public class BaseStorageService {

    private String active;

    private StorageType storageType;

    @Resource
    private StorageService storageService;

    /**
     *  图片存储
     *
     * @param inputStream 图片流
     * @param contentLength 图片大小
     * @param contentType 图片的类型
     * @param fileName 图片原名称
     * @author hanyulin
     * @date 2021/12/4 11:24
     * @return PicStorageEntity
     */
    public PicStorageEntity store(InputStream inputStream, long contentLength, String contentType, String fileName) {
        /*
         * 产生图片唯一标识符号
         */
        String key = generateKey(fileName);
        /*
         * 调用接口StorageType的store实现文件存储
         */
        storageType.store(inputStream, contentLength, contentType, key);
        /*
         * 图片信息的存储
         */
        PicStorageEntity picStorage = new PicStorageEntity();
        picStorage.setName(fileName);
        picStorage.setSize((int) contentLength);
        picStorage.setType(contentType);
        picStorage.setPicKey(key);
        picStorage.setUrl(storageType.generateUrl(key));
        storageService.insert(picStorage);
        return picStorage;
    }

    private String generateKey(String originalFilename) {
        int index = originalFilename.lastIndexOf('.');
        String suffix = originalFilename.substring(index);

        String key = null;
        PicStorageEntity storageInfo = null;

        do {
            key = CharUtil.getRandomString(20) + suffix;
            storageInfo = storageService.findByKey(key);
        }
        while (storageInfo != null);

        return key;
    }

    /**
     * 删除
     *
     * @param key 唯一标识符
     * @author hanyulin
     * @date 2021/12/6 9:13
     */
    public void delete(String key){
        storageType.delete(key);
        storageService.delete(key);
    }

}
